package com.itheima.controller;

import com.aliyun.tea.*;
import com.aliyun.teaopenapi.models.*;
import com.aliyun.teautil.models.*;
import com.itheima.common.R;
import com.itheima.pojo.Login;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.*;

/**
 * @author 林晓伟
 */
@RestController
@RequestMapping("/user")
public class AliyunSms {
    @Resource
    RedisTemplate<String,String> redisTemplate;

    public static com.aliyun.dysmsapi20170525.Client createClient( String accessKeyId, String accessKeySecret ) throws Exception {
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
    @PostMapping("/sendMsg")
    public R aliyun(@RequestBody Login phone) throws Exception {
        String phone1 = phone.getPhone();
        //生成四位随机数 并存入redis
        Random random = new Random();
        String randomCode= String.valueOf(random.nextInt(9999-1000+1)+1000);
        redisTemplate.opsForValue().set("code", randomCode);
        com.aliyun.dysmsapi20170525.Client client = AliyunSms.createClient("LTAI5tL6sGF8uPfHVdJcxXWB","OITrc3ThnRQ5K5xMQpmJ41yMpLkca1");
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers(phone1)
                .setTemplateParam("{\"code\":\"" + randomCode + "\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return R.success("手机验证码短信发送成功");
    }
}
